package com.jichangxiu.common.utils;

import com.jichangxiu.common.entity.bo.SecurityUser;
import com.jichangxiu.common.exception.FrameworkException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtils {

    /**
     * @return 获取 Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * @return 获取用户
     */
    public static SecurityUser getSecurityUser() {
        try {
            return (SecurityUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            throw FrameworkException.build("获取用户信息异常", e);
        }
    }

    /**
     * @return 获取用户ID
     */
    public static String getUserId() {
        try {
            return getSecurityUser().getRecord().getStr("userId");
        } catch (Exception e) {
            throw FrameworkException.build("获取用户ID异常", e);
        }
    }

    /**
     * @return 获取获取部门ID
     */
    public static String getDeptId() {
        try {
            return getSecurityUser().getRecord().getStr("deptId");
        } catch (Exception e) {
            throw FrameworkException.build("获取部门ID异常", e);
        }
    }

    /**
     * @return 获取用户账户
     */
    public static String getUsername() {
        try {
            return getSecurityUser().getUsername();
        } catch (Exception e) {
            throw FrameworkException.build("获取用户账户异常", e);
        }
    }

}
